package com.example.minefieldkeepercloud.util.netty;

import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 解码
 * Created by Administrator on 2018/3/22.
 */

public class NewDecoder extends LengthFieldBasedFrameDecoder {

    /**
     * 我们在Message类中定义了type和length，这都放在消息头部
     * type占1个字节，length占4个字节所以头部总长度是5个字节
     */
    private static final int HEADER_SIZE = 5;
    private byte type;
    private int length;
    private String msgBody;


    /**
     * @param maxFrameLength      网络字节序，默认为大端字节序
     * @param lengthFieldOffset   消息中长度字段偏移的字节数
     * @param lengthFieldLength   数据帧的最大长度
     * @param lengthAdjustment    该字段加长度字段等于数据帧的长度
     * @param initialBytesToStrip 从数据帧中跳过的字节数
     * @param failFast            如果为true，则表示读取到长度域，TA的值的超过maxFrameLength，就抛出一个 TooLongFrameException
     */
    public NewDecoder(int maxFrameLength, int lengthFieldOffset,
                      int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip,
                      boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
                lengthAdjustment, initialBytesToStrip, failFast);
    }


    private boolean isLong=true;
    private int lengthed=0;//已读长度
    private int alllength=0;//总长度
    private byte[] allreq;//总数组


    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        if (in == null) {
            return null;
        }

        byte[] req = new byte[in.readableBytes()];
        in.readBytes(req);

        int targets=(req[0]&0xff)|((req[1]<<8)&0xff00)//|表示安位或

                |((req[2]<<24)>>>8)|(req[3]<<24);


        int le = ((int)(targets & (0x00 << 22 | 0x3fffff)))+4;




        if (alllength==0)
        {
            if (le>in.readableBytes())
            {
                isLong=false;
                alllength=le;

            }
            allreq=new byte[le];
        }

        System.arraycopy(req, 0, allreq, lengthed, req.length);
        lengthed=req.length+lengthed;



        if (lengthed==alllength)
        {
            isLong=true;
            alllength=0;
            lengthed=0;

        }

        if (isLong&&allreq.length > 4) {

            byte b = allreq[4];



            String data = new String(allreq, 5, allreq.length - 5);
            Log.i("-->", "NewDecoder返回的mt:" + b + "  json:" + data);
            Message msg = new Message(b, data);
            return msg;
        }

//====================================================================================================

        return null;
    }
}
